Completed
Pull Request — master (#99)
by Johan
01:15
created

EAN5.js ➔ ... ➔ ???   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
c 4
b 0
f 0
nc 1
nop 1
dl 0
loc 17
rs 9.4285
1
// Encoding documentation:
2
// https://en.wikipedia.org/wiki/EAN_5#Encoding
3
4
import EANencoder from './ean_encoder.js';
5
6
class EAN5{
7
	constructor(string){
8
		this.string = string;
9
10
		// Define the EAN-13 structure
11
		this.structure = [
12
			"GGLLL",
13
			"GLGLL",
14
			"GLLGL",
15
			"GLLLG",
16
			"LGGLL",
17
			"LLGGL",
18
			"LLLGG",
19
			"LGLGL",
20
			"LGLLG",
21
			"LLGLG"
22
		];
23
	}
24
25
	valid(){
26
		return this.string.search(/^[0-9]{5}$/) !== -1;
27
	}
28
29
	encode(){
30
		var encoder = new EANencoder();
31
		var checksum = this.checksum();
32
33
		// Start bits
34
		var result = "1011";
35
36
		// Use normal ean encoding with 01 in between all digits
37
		result += encoder.encode(this.string, this.structure[checksum], "01");
38
39
		return {
40
			data: result,
41
			text: this.string
42
		};
43
	}
44
	
45
	checksum(){
46
		var result = 0;
47
48
		result += parseInt(this.string[0]) * 3;
49
		result += parseInt(this.string[1]) * 9;
50
		result += parseInt(this.string[2]) * 3;
51
		result += parseInt(this.string[3]) * 9;
52
		result += parseInt(this.string[4]) * 3;
53
54
		return result % 10;
55
	}
56
}
57
58
export default EAN5;
59